package com.h3c.ptability.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.h3c.ptability.client.EosSyncDataClient;
import com.h3c.ptability.mapper.BdPublicCalendarMapper;
import com.h3c.ptability.entity.BdPublicCalendar;
import com.h3c.ptability.service.IBdPublicCalendarService;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.utils.AppBusinessException;
import com.xxl.job.core.log.XxlJobLogger;
import groovy.util.logging.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 公共日历表(BdPublicCalendar)表服务实现类
 *
 * @author makejava
 * @since 2022-07-06 13:42:49
 */
@Service
@Slf4j
public class BdPublicCalendarServiceImpl extends ServiceImpl<BdPublicCalendarMapper, BdPublicCalendar> implements IBdPublicCalendarService {

    @Resource
    private EosSyncDataClient eosSyncDataClient;
    @Resource
    private CommService commService;

    Logger logger = LoggerFactory.getLogger(BdPublicCalendarServiceImpl.class);

    @Override
    public List<String> queryFestivalByDate(String solarDateStart, String solarDateEnd) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date start = format.parse(solarDateStart);
            Date end = format.parse(solarDateEnd);
            QueryWrapper<BdPublicCalendar> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().ge(BdPublicCalendar::getSolarDate, start).le(BdPublicCalendar::getSolarDate, end);
            List<BdPublicCalendar> list = list(queryWrapper);
            return list.stream().filter(o -> Objects.equals(o.getNationalWorkday(), "0"))
                    .map(o -> format.format(o.getSolarDate()))
                    .collect(Collectors.toList());
        } catch (ParseException e) {
            logger.error("查询日历异常：", e);
            throw new AppBusinessException("查询异常：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public void syncBdPublicCalendar() {
        String eosToken = "Bearer " + commService.getEosToken();
        XxlJobLogger.log("获取token成功");
        JSONObject response = eosSyncDataClient.getPublicCalendar(eosToken);
        String code = response.getString("code");
        String message = response.getString("message");
        logger.info("message= {}", message);
        if ("20216".equals(code)) {
            JSONArray array = response.getJSONArray("data");
            int count = 0;
            List<BdPublicCalendar> list = new ArrayList<>();
            for (Object o : array) {
                BdPublicCalendar publicCalendar = getPublicCalendar(o);
                list.add(publicCalendar);
                count++;
                if (count >= 500) {
                    saveOrUpdateBatch(list);
                    count = 0;
                    list.clear();
                }
            }
            if (!list.isEmpty()) {
                saveOrUpdateBatch(list);
            }
        } else {
            XxlJobLogger.log("接口返回错误：response={}", response);
        }
    }

    private BdPublicCalendar getPublicCalendar(Object o) {
        JSONObject obj = (JSONObject) o;
        BdPublicCalendar publicCalendar = new BdPublicCalendar();
        publicCalendar.setDateId(obj.getString("date_id"));
        publicCalendar.setSolarDate(obj.getDate("solar_date"));
        publicCalendar.setLunarDate(obj.getString("lunar_date"));
        publicCalendar.setWeek(obj.getString("week"));
        publicCalendar.setMonth(obj.getString("month"));
        publicCalendar.setQuarter(obj.getString("quarter"));
        publicCalendar.setYear(obj.getString("year"));
        publicCalendar.setDwNumber(obj.getInteger("dw_number"));
        publicCalendar.setDmNumber(obj.getInteger("dm_number"));
        publicCalendar.setDyNumber(obj.getInteger("dy_number"));
        publicCalendar.setWyNumber(obj.getInteger("wy_number"));
        publicCalendar.setMyNumber(obj.getInteger("my_number"));
        publicCalendar.setFestival(obj.getString("festival"));
        publicCalendar.setNationalWorkday(obj.getString("national_workday"));
        publicCalendar.setDwStatus(obj.getString("dw_status"));
        publicCalendar.setLoadedTime(obj.getDate("loaded_time"));
        return publicCalendar;
    }

}

